<template>
  <el-container class="main_con">
    <div class="filter_con nopt">
      <div class="filter_area">
        <!-- <el-input class="serach_input mr_15" size="medium" placeholder="商品名称" style="width:300px;"></el-input> -->
        <el-input size="medium" v-model="obj.keyword" placeholder="请输入搜索内容" class="mr_15 mt_15" style="width:400px;">
          <el-select v-model="obj.type" slot="prepend" placeholder="请选择" style="width:130px;">
            <el-option v-for="item in type" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-input>

        <label class="mr_15 mt_15">支付方式</label>
        <el-select v-model="obj.pay_type" size="medium" placeholder="请选择" class="mr_15 mt_15">
          <el-option v-for="item in pay_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>

        <label class="mr_15 mt_15">状态</label>
        <el-select v-model="obj.status" size="medium" placeholder="请选择" class="mr_15 mt_15">
          <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>

        <label class="mr_15 mt_15">创建时间</label>
        <date-picker size="medium" @change="getTime" class="mr_15 mt_15"></date-picker>
        <el-button class="mr_15 mt_15" @click="searchList" size="medium">搜索</el-button>
      </div>
    </div>
    <div class="list_con">
      <div class="orderlist">
        <div class="order_head">
          <table cellspacing="0" cellpadding="0" width="100%">
            <colgroup>
              <col width="500" />
              <col width="200" />
              <col width="180" />
              <col width="180" />
              <col />
              <col width="180" />
              <col width="150" />
              <col width="130" />
            </colgroup>
            <tbody>
              <tr>
                <td>商品</td>
                <td>单价/数量</td>
                <td>电子面单打印状态</td>
                <td>收货人</td>
                <!-- <td>收货地址</td> -->
                <td>实付款</td>
                <td>支付/配送</td>
                <td>状态</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="order" v-for="(item, i) in list" :key="i">
          <div class="header">
            <div class="txt">
              <!-- <el-checkbox size="medium"  :indeterminate="isIndeterminate" v-model="item.selected" style="margin-right:15px;"></el-checkbox> -->
              <el-checkbox
                size="medium"
                :indeterminate="
                  item.orderCommoditys.filter(_ => _.selected).length == 0 || item.orderCommoditys.filter(_ => _.selected).length == item.orderCommoditys.length ? false : true
                "
                v-model="item.selected"
                @change="selectAll($event, i)"
                style="margin-right:15px;"
              ></el-checkbox>
              <div class="info">下单时间：{{ item.create_time }}</div>
              <div class="info">订单编号：{{ item.order_no }}</div>
              <div class="info"><el-button style="font-size:12px;" type="text" @click="doCopy(item.order_no)">复制</el-button></div>
            </div>
          </div>
          <div class="content">
            <table cellspacing="0" cellpadding="1" border="1" bordercolor="#dcdfe6" style="border-collapse:collapse;" width="100%">
              <colgroup>
                <col width="500" />
                <col width="200" />
                <col width="180" />
                <col width="180" />
                <!-- <col /> -->
                <col width="180" />
                <col width="150" />
                <col width="130" />
              </colgroup>
              <tbody>
                <tr v-for="(sitem, l) in item.orderCommoditys" :key="l">
                  <td>
                    <div class="pro">
                      <el-checkbox
                        size="medium"
                        :disabled="sitem.after_status != '3'"
                        v-model="sitem.selected"
                        style="margin-right:15px;"
                        @change="selectSingle($event, i, l)"
                      ></el-checkbox>
                      <div class="img"><vimage style="width: 40px; height: 40px;" :src="sitem.master" fit="fit"></vimage></div>
                      <div class="txt">
                        <div class="name">
                          <span :class="'t' + sitem.type">{{ sitem.type == 0 ? '实' : '虚' }}</span>
                          {{ sitem.name }}
                        </div>
                        <div class="class">{{ sitem.pvs_value_new }}</div>
                        <el-popover placement="top-start" title="附加规格
                        " width="400" trigger="hover" >
                          <el-table :data="sitem.attachlist" >
                            <el-table-column  property="attach_value" label="附加"></el-table-column>
                            <el-table-column  property="num" label="数量"></el-table-column>
                            <el-table-column  property="attach_price" label="单价"></el-table-column>
                          </el-table>
                          <!--  <el-button >hover 激活</el-button> -->
                          <div slot="reference" v-if="sitem.attachlist && sitem.attachlist.length > 0">附加x{{ sitem.attachlist.length }},共￥{{ sitem.attach_pirce }}</div>
                        </el-popover>
                      </div>
                    </div>
                  </td>
                  <td>
                    ￥{{ sitem.sell_price }}
                    <br />
                    X{{ sitem.count }}
                  </td>
                  <td>{{ sitem.is_print }}{{ sitem.after_status != '3' ? '（维权订单,不可打印）' : '' }}</td>

                  <td v-if="item.orderCommoditys.length == 1 || l == 0" :rowspan="item.orderCommoditys.length">
                    <span style="cursor: pointer">
                      {{ item.user_real_name }}
                      <br />
                      {{ item.user_mobile }}
                    </span>
                  </td>
                  <!-- <td v-if="item.orderCommoditys.length == 1 || l == 0" :rowspan="item.orderCommoditys.length">{{ item.address }}</td> -->
                  <td v-if="item.orderCommoditys.length == 1 || l == 0" :rowspan="item.orderCommoditys.length">
                  <!--  ￥{{ item.money }}
                    <br />
                    (含运费：￥0.00) -->
                    <el-popover placement="top" title="" width="170" trigger="hover">
                      <div class="pricecount">
                        <div>
                          <span>商品小计:</span>
                          <span>{{ item.orderItemCountPrice }}</span>
                        </div>
                        <div>
                          <span>运费:</span>
                          <span>￥{{ item.freight || '0.00' }}</span>
                        </div>
                        <div>
                          <span>优惠抵扣:</span>
                          <span>￥{{ item.discount || '0.00' }}</span>
                        </div>
                        <div>
                          <span>积分抵扣:</span>
                          <span>￥{{ item.discount_amount || '0.00' }}</span>
                        </div>

                        <div>
                          <span>会员折扣:</span>
                          <span>￥{{ item.discount_level_money }}</span>
                        </div>
                        <div>
                          <span>实付款:</span>
                          <span style=" color: #f56c6c;">￥{{ item.money }}</span>
                        </div>
                      </div>

                      <span slot="reference">
                        ￥{{ item.money }}
                        <br />
                        (含运费：￥{{ item.freight || '0.00' }})
                      </span>
                    </el-popover>
                  </td>
                  <!-- <td v-if="item.orderCommoditys.length == 1 || l == 0" :rowspan="item.orderCommoditys.length">后台确认<br/>快递</td> -->
                  <td v-if="item.orderCommoditys.length == 1 || l == 0" :rowspan="item.orderCommoditys.length">
                    {{ item.pay_id }}
                    <br />
                    {{ item.order_type == 1 ? '快递' : '自提' }}
                  </td>
                  <td v-if="item.orderCommoditys.length == 1 || l == 0" :rowspan="item.orderCommoditys.length">
                    {{ item.status }}
                    <br />
                    {{ item.is_print }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div class="order_empty" v-if="list.length == 0">暂无数据</div>
      </div>
      <div class="table_footer" style="justify-content: flex-end;" v-if="total != 0">
        <el-pagination @current-change="changePage" class="pages" background hide-on-single-page layout="prev, pager, next" :total="total"></el-pagination>
      </div>
    </div>

    <div class="footer_btn">
      <el-button type="primary" v-has size="medium" @click="printElectronic">电子面单</el-button>
      <el-button type="primary" v-has size="medium" @click="printReceipt">小票</el-button>
      <el-button type="primary" v-has size="medium" @click="printinvoice">发货单</el-button>
      <!-- <el-button type="primary" size="medium">发货单</el-button>
      <el-button type="danger" size="medium">同时打印</el-button> -->
    </div>

    <el-dialog title="打印面单" :visible.sync="showPrint" width="30%" @close="clearData" destroy-on-close>
      选择模板：
      <el-select size="medium" v-model="pso.template_id" placeholder="请选择模板">
        <el-option v-for="item in templateList" :key="item.id" :label="item.default ? item.name + '(默认)' : item.name" :value="item.id"></el-option>
      </el-select>

      <el-button type="primary" size="medium" style="margin-left:15px" @click="printElectronicFun">打印数据</el-button>
    </el-dialog>
    <el-dialog title="打印发货单" :visible.sync="showPrintinvoice" width="30%" @close="clearData" destroy-on-close>
      选择模板：
      <el-select size="medium" v-model="posInv.template_id" placeholder="请选择模板">
        <el-option v-for="item in invoicetemplateList" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>

      <el-button type="primary" size="medium" style="margin-left:15px" @click="printinvoiceFun">打印数据</el-button>
    </el-dialog>
    <el-dialog title="打印小票" :visible.sync="showPrintReceipt" width="30%" @close="clearDataRec" destroy-on-close>
      <div class="psoRec_item">
        <div class="label">选择模板：</div>
        <div class="content">
          <el-select size="medium" v-model="psoRec.template_id" placeholder="请选择模板">
            <el-option v-for="item in templateRecList" :key="item.id" :label="item.default ? item.name + '(默认)' : item.name" :value="item.id"></el-option>
          </el-select>
        </div>
      </div>

      <div class="psoRec_item">
        <div class="label">选择打印机：</div>
        <div class="content">
          <el-select size="medium" v-model="psoRec.printer_id" placeholder="请选择模板">
            <el-option v-for="item in templateList" :key="item.id" :label="item.default ? item.name + '(默认)' : item.name" :value="item.id"></el-option>
          </el-select>
        </div>
      </div>

      <el-button type="primary" size="medium" style="margin-left:15px" @click="printRecFun">打印数据</el-button>
    </el-dialog>
  </el-container>
</template>

<script>
import DatePicker from '@/components/DatePicker/index';
import {getLodop} from '@/utils/lodop';
import {PrintAccount} from '@/utils/lodop_print';
import {getOrderList} from '@/api/shop/order';
import {createExpressBill, createinvoiceBill, getEBTemplateList, createReceipt, getReceiptTemplateList, getReceiptPrinterList, getinvoiceList} from '@/api/shop/print';

export default {
  data() {
    return {
      showPrintReceipt: false,
      templateRecList: [],
      templateList: [],
      showPrint: false,
      showPrintinvoice: false,
      type: [
        {
          value: '7',
          label: '订单编号'
        },
        {
          value: '1',
          label: '用户ID'
        },
        {
          value: '2',
          label: '用户信息'
        },
        {
          value: '3',
          label: '收件人信息'
        },
        {
          value: '4',
          label: '地址信息'
        },
        {
          value: '5',
          label: '商品名称'
        },
        {
          value: '6',
          label: '商品编号'
        }
      ],
      pay_type: [
        {
          value: '',
          label: '全部'
        },
        {
          value: 1,
          label: '余额'
        },
        {
          value: 2,
          label: '微信'
        },
        {
          value: 3,
          label: '支付宝'
        },
        {
          value: 4,
          label: '后台支付'
        }
      ],
      status: [
        {
          value: '',
          label: '全部'
        },

        {
          value: '2',
          label: '待发货'
        },
        {
          value: '3',
          label: '已发货'
        },
        {
          value: '4',
          label: '已完结'
        }
      ],
      obj: {
        type: '7',
        keyword: '',
        pay_type: '',
        status: '',
        order_type: 1, //订单类型,1快递,2自提
        start_time: '',
        end_time: '',
        page: 1,
        size: 10,
        is_print_list:1
      },
      objTemp: {},
      pso: {
        order_id: [],
        order_commodity_id: [],
        template_id: ''
      },
      psoRec: {
        order_id: [],
        printer_id: '',
        template_id: ''
      },
      posInv: {
        order_id: [],
        template_id: ''
      },
      invoicetemplateList: [],
      total: 0,
      isLoading: false,
      list: [],
      listSelected: []
    };
  },
  components: {
    DatePicker
  },
  created() {
    if (this.$route && this.$route.query && this.$route.query.order_no) {
      // console.log(this.$route);
      this.obj.keyword = this.$route.query.order_no;
      this.obj.type = '7';
    }
    this.getTemplateList();
    this.getTemplateRecList();
    this.getinvoicetemplateList();
  },
  mounted() {
    this.searchList();
  },
  methods: {
    getinvoicetemplateList() {
      getinvoiceList({page: 1, size: 100})
        .then(res => {
          this.invoicetemplateList = res.msg.data;
        })
        .catch(e => {});
    },
    //复制单号
    doCopy(orderNo) {
      this.$copyText(orderNo).then(
        res => {
          this.$message({
            message: '复制成功',
            type: 'success',
            duration: 2000
          });
        },
        error => {
          this.$alert('无法复制');
        }
      );
    },
    //获取所有打印模板
    getTemplateList() {
      getEBTemplateList()
        .then(res => {
          this.templateList = res.msg;
        })
        .catch(e => {
          //empty
        });
    },
    //获取所有打印模板(小票)
    getTemplateRecList() {
      getReceiptTemplateList()
        .then(res => {
          this.templateRecList = res.msg;
        })
        .catch(e => {
          //empty
        });
    },
    //获取时间
    getTime(value) {
      this.obj.start_time = value[0];
      this.obj.end_time = value[1];
    },
    //查询数据
    searchList() {
      //复制查询对象
      this.objTemp = Object.assign({}, this.obj);
      this.getDataList();
    },
    //查询数据本体
    getDataList() {
      this.isLoading = true;
      getOrderList(this.objTemp)
        .then(res => {
          this.isLoading = false;
          let o = res.msg;
          //处理sku规格数据,处理全选数据
          o.data.forEach(e => {
            this.$set(e, 'selected', false);
            e.orderItemCountPrice = 0;
            e.orderCommoditys.forEach(x => {
              this.$set(x, 'selected', false);
              if (x.pvs_value) {
                //转换处理SKU数据->红+L+大
                let l = x.pvs_value.split(','),
                  s = '';
                l.forEach(k => {
                  s += k.split(':')[1] + '+';
                });
                s = s.substring(0, s.length - 1);
                x.pvs_value_new = s;
              }
              e.orderItemCountPrice += x.sell_price * x.count;
              if (e.attach && e.attach.length > 0 && x.attach_value && x.attach_value != '') {
                x.attachlist = [];
                x.attach_pirce = 0;

                e.attach.forEach(a => {
                  if (x.attach_value.indexOf(a.attach_value) > -1 && x.attachlist.findIndex(_ => _.attach_value == a.attach_value) == -1) {
                    x.attachlist.push(a);
                    x.attach_pirce += Number(a.attach_price) * a.num;
                  }
                });
                 e.orderItemCountPrice += x.attach_pirce;
                x.attach_pirce = x.attach_pirce.toFixed(2);
              }

            });
             e.orderItemCountPrice = e.orderItemCountPrice.toFixed(2);
          });
          this.list = o.data;
          this.total = o.total;
        })
        .catch(e => {
          this.isLoading = false;
        });
    },
    //查看订单详情
    showOrder(id) {
      this.$router.push({path: '/order/item', query: {id: id, k: Math.random()}});
    },
    //切换分页
    changePage(page) {
      //清空选中记录数组
      //this.listSelected = [];

      this.objTemp.page = page;
      this.getDataList();
    },
    //全选
    selectAll(e, i) {
      if (e) {
        this.list[i].orderCommoditys.forEach(e => {
          if (e.after_status == '3') {
            e.selected = true;
          }
        });
      } else {
        this.list[i].orderCommoditys.forEach(e => {
          e.selected = false;
        });
      }
    },
    //单选
    selectSingle(e, i, l) {
      if (e) {
        if (this.list[i].orderCommoditys.length == this.list[i].orderCommoditys.filter(_ => _.selected && _.after_status != '3').length) {
          this.list[i].selected = true;
        }
      } else {
        this.list[i].selected = false;
      }
    },
    //打印小票关闭自动清空模板选择数据
    clearDataRec() {
      this.psoRec.template_id = '';
      this.psoRec.printer_id = '';
    },
    //打印小票
    printRecFun() {
      if (this.psoRec.template_id && this.psoRec.printer_id) {
        createReceipt(this.psoRec)
          .then(res => {
            this.$message({
              message: '操作完毕,请等待打印结果',
              type: 'success'
            });
            this.showPrintReceipt = false;
          })
          .catch(e => {
            //empty
          });
      } else {
        this.$alert('请先选择打印模板与打印机');
        return false;
      }
    },
    printReceipt() {
      let flag = false;
      let order_id = [];

      //封装数据
      this.list.forEach(e => {
        e.orderCommoditys.forEach(x => {
          if (x.selected) {
            flag = true;
            //封装订单id
            if (order_id.findIndex(_ => _ == e.id) == -1) {
              //确保数据组不会有重复的订单id
              order_id.push(e.id);
            }
          }
        });
      });

      this.psoRec.order_id = order_id;
      if (!flag) {
        this.$alert('请先选择商品再打印');
        return false;
      } else {
        this.showPrintReceipt = true;
      }
    },
    //打印面单关闭自动清空模板选择数据
    clearData() {
      this.pso.template_id = '';
      //this.pso.order_id = [];
      //this.pso.order_commodity_id = [];
    },
    //打印电子面单
    printElectronicFun() {
      if (this.pso.template_id) {
        createExpressBill(this.pso)
          .then(res => {
            //empty
            PrintAccount(res.msg, 1);
            //LODOP.PRINT()
            LODOP.PREVIEW();
          })
          .catch(e => {
            //empty
          });
      } else {
        this.$alert('请选择打印模板');
        return false;
      }
    },
    printinvoiceFun() {
      if (this.posInv.template_id) {
        createinvoiceBill(this.posInv)
          .then(res => {
            //empty
            PrintAccount(res.msg, 2);
            //LODOP.PRINT()
            LODOP.PREVIEW();
          })
          .catch(e => {
            //empty
          });
      } else {
        this.$alert('请选择打印模板');
        return false;
      }
    },
    printElectronic() {
      let flag = false;
      let order_id = [];
      let order_commodity_id = [];

      //封装数据
      this.list.forEach(e => {
        e.orderCommoditys.forEach(x => {
          if (x.selected) {
            flag = true;
            //封装商品id
            order_commodity_id.push(x.order_commodity_id);
            //封装订单id
            if (order_id.findIndex(_ => _ == e.id) == -1) {
              //确保数据组不会有重复的订单id
              order_id.push(e.id);
            }
          }
        });
      });

      this.pso.order_id = order_id;
      this.pso.order_commodity_id = order_commodity_id;

      if (!flag) {
        this.$alert('请先选择商品再打印');
        return false;
      } else {
        this.showPrint = true;
      }
    },
    printinvoice() {
      let flag = false;
      let order_id = [];
      let order_commodity_id = [];

      //封装数据
      this.list.forEach(e => {
        e.orderCommoditys.forEach(x => {
          if (x.selected) {
            flag = true;
            //封装商品id
            order_commodity_id.push(x.order_commodity_id);
            //封装订单id
            if (order_id.findIndex(_ => _ == e.id) == -1) {
              //确保数据组不会有重复的订单id
              order_id.push(e.id);
            }
          }
        });
      });

      this.posInv.order_id = order_id;
      this.posInv.order_commodity_id = order_commodity_id;

      if (!flag) {
        this.$alert('请先选择商品再打印');
        return false;
      } else {
        this.showPrintinvoice = true;
      }
    }
    //打印发货单
    //同时打印
  }
};
</script>

<style lang="scss" scoped>
.proImg {
  display: flex;
  align-items: center;
}

.list_con {
  //height: calc(100vh - 50px - 20px - 66px - 15px - 20px - 70px);
  height: calc(100vh - 241px);
  overflow-y: auto;
}

//订单列表
.orderlist {
  width: 100%;
  display: flex;
  flex-direction: column;
  font-size: 12px;

  .order_head {
    border-bottom: 1px solid #dcdfe6;
    font-weight: 700;
    color: #909399;
    //font-size: 14px;

    table {
      tr {
        td {
          padding: 10px 20px 20px;
          // text-align: center;
        }
      }
    }
  }

  .order_empty {
    color: #c0c4cc;
    //font-size: 14px;
    text-align: center;
    height: 50px;
    line-height: 50px;
  }

  .order {
    margin-top: 15px;

    &:first-child {
      margin-top: 0;
    }

    .header {
      background-color: #f4f6f8;
      height: 40px;
      line-height: 40px;
      display: flex;
      border: 1px solid #dcdfe6;
      border-bottom: 0;
      padding-left: 10px;
      color: #909399;
      //font-size: 14px;

      .txt {
        flex: 1;

        .info {
          display: inline-block;
          margin-right: 15px;
        }
      }

      .button {
        width: 300px;
        text-align: right;
        padding-right: 20px;
      }
    }

    .content {
      background: #dcdfe6;
      //font-size: 14px;
      color: #606266;

      table {
        background: #fff;

        tr {
          td {
            padding: 5px 10px;
            line-height: 28px;
            //border: 1px solid #DCDFE6;

            .pro {
              display: flex;
              align-items: center;

              .img {
                width: 40px;
                height: 40px;
                margin-right: 10px;
              }

              .txt {
                flex: 1;
                display: flex;
                flex-direction: column;
                align-content: space-between;

                .name {
                  .t0 {
                    color: #409eff;
                    font-weight: 700;
                    margin-right: 5px;
                  }

                  .t1 {
                    color: #f56c6c;
                    font-weight: 700;
                    margin-right: 5px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

.footer_btn {
  display: flex;
  align-items: center;
  height: 70px;
  padding: 0 20px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
}

.psoRec_item {
  display: flex;
  align-items: center;
  margin-bottom: 22px;

  .label {
    width: 100px;
    text-align: right;
  }

  .content {
    flex-grow: 1;
  }
}
.pricecount{
  div{
    padding: 5px 0;
    span:first-child{
      display: inline-block;
      width: 75px;
       text-align: right;
       margin-right: 5px;
    }
  }
}
</style>
